import 'package:get/get.dart';
import 'package:pornhub_app/views/ai/common/popup/ai_wxts_image_dialog.dart';

import '../../../../components/base_refresh/base_refresh_simple_controller.dart';
import '../../../../components/popup/dialog/future_loading_dialog.dart';
import '../../../../http/api/api.dart';
import '../../../../http/api_code.dart';
import '../../../../model/ai/ai_models.dart';
import '../../../../services/user_service.dart';
import '../../../../utils/consts.dart';
import '../../../../utils/enum.dart';
import '../../common/ai_bytes_image.dart';
import '../../common/popup/ai_cost_gold_confirm_dialog.dart';
import '../../common/popup/ai_no_image_tips_dialog.dart';

const _pageSize = 60;
const _useObs = true;

class AiTabFaceImagePageController
    extends BaseRefreshSimpleController<AiStencilModel> with StateMixin<void> {
  @override
  bool get useObs => _useObs;

  @override
  Future<List<AiStencilModel>?> dataFetcher(int page,
      {required bool isRefresh}) {
    return Api.fetchAiFaceImageStencil(page: page, pageSize: _pageSize);
  }

  @override
  bool noMoreChecker(List<AiStencilModel> resp) => resp.length < _pageSize;

  void onTapMake(AiStencilModel stencil, AiBytesImage? file) async {
    if (file == null) {
      AiNoImageTipsDialog().show();
      return;
    }
    AiWxtsImageDialog(
      onConfirm: () {
        final userService = Get.find<UserService>();
        final costType = userService.checkAiCost(
          costAiNum: Consts.aiFaceImageCostCount,
          costGold: Consts.aiFaceImageCostGold,
        );
        if (costType == AiCostType.fail) {
          ApiCode.defaultGoldLackHandler();
        } else if (costType == AiCostType.gold) {
          AiCostGoldConfirmDialog.faceImage(
            Consts.aiFaceImageCostGold,
            onConfirm: () => _onMakeConfirm(stencil, file),
          ).show();
        } else {
          _onMakeConfirm(stencil, file);
        }
      },
    ).show();
  }

  void _onMakeConfirm(AiStencilModel stencil, AiBytesImage file) async {
    final future = Api.createAiFaceImageOrder(stencil.stencilId, file.bytes);
    final resp = await FutureLoadingDialog(future).showUnsafe();
    ApiCode.handle(resp, successToast: '提交成功', onSuccess: () => Get.back());
  }
}
